package com.zhongkun.datahome.service.export.handler;

import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.*;

/**
 * @Author: lifengsheng
 * @Date: 2025/5/12 11:21
 * @Desc
 */
public class AddNoHandler implements RowWriteHandler {
    private final String headerName; // 表头名称，如"序号"
    private final int columnIndex;   // 列索引，如 0（第一列）
    private int rowIndex = 1;        // 从 1 开始

    public AddNoHandler(String headerName, int columnIndex) {
        this.headerName = headerName;
        this.columnIndex = columnIndex;
    }

    @Override
    public void afterRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
                               Row row, Integer relativeRowIndex, Boolean isHead) {
        if (isHead) {
            // 处理标题行：插入“序号”表头
            Cell cell = row.createCell(columnIndex);
            cell.setCellValue(headerName);

            // 设置列宽（单位：1/256 字符宽度）
            writeSheetHolder.getSheet().setColumnWidth(columnIndex, 6 * 256); // 6个字符宽度
        } else {
            // 处理数据行：插入行号（从1开始）
            Cell cell = row.createCell(columnIndex);
            cell.setCellValue(rowIndex++);
        }
    }

    @Override
    public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Integer relativeRowIndex, Boolean isHead) {
        Cell noCell = row.getCell(0); // 序号列
        Cell refCell = row.getCell(1); // 参考列（第二列）

        // 复制参考列样式到序号列
        if (refCell != null) {
            CellStyle refStyle = refCell.getCellStyle();
            noCell.setCellStyle(refStyle);
        }
    }
}